<template>
  <div ref="chartRef" style="width: 100%; height: 500px;"></div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, inject, watch } from 'vue';
// 导入全局配置好的 echarts
import echarts from '@/utils/echarts-config';

const chartRef = ref(null);
let chartInstance = null;
let isDestroyed = false; // 添加销毁标志

// 获取屏幕尺寸信息
const screenSize = inject('screenSize', ref({
  width: window.innerWidth,
  height: window.innerHeight,
  isMobile: window.innerWidth <= 768,
  isTablet: window.innerWidth > 768 && window.innerWidth <= 1024,
  isDesktop: window.innerWidth > 1024
}));

// 监听屏幕尺寸变化
watch(screenSize, (newSize) => {
  if (chartInstance && !isDestroyed) {
    setTimeout(() => {
      handleResize();
    }, 100);
  }
}, { deep: true });

const getGlobeOption = () => ({
  backgroundColor: '#000',
  title: { 
    text: '3D地球可视化', 
    textStyle: { color: '#00eaff' },
    left: 'center'
  },
  globe: {
    baseTexture: '/echarts-gl-assets/world.topo.bathy.200401.jpg',
    heightTexture: '/echarts-gl-assets/world.topo.bathy.200401.jpg',
    displacementScale: 0.04,
    shading: 'realistic',
    environment: '/echarts-gl-assets/starfield.jpg',
    realisticMaterial: {
      roughness: 0.9
    },
    postEffect: {
      enable: true
    },
    light: {
      main: {
        intensity: 5,
        shadow: true
      },
      ambientCubemap: {
        texture: '/echarts-gl-assets/pisa.hdr',
        diffuseIntensity: 0.2
      }
    }
  }
});

// 优化 resize 处理
const handleResize = () => {
  if (chartInstance && !isDestroyed) {
    try {
      chartInstance.resize();
    } catch (error) {
      console.warn('Resize error:', error);
    }
  }
};

// 暴露 resize 方法给父组件
defineExpose({
  handleResize
});

onMounted(() => {
  isDestroyed = false;
  if (chartRef.value) {
    try {
      chartInstance = echarts.init(chartRef.value);
      chartInstance.setOption(getGlobeOption());
      window.addEventListener('resize', handleResize);
    } catch (error) {
      console.error('3D地球初始化失败:', error);
    }
  }
});

onBeforeUnmount(() => {
  isDestroyed = true;
  
  // 先移除事件监听器
  window.removeEventListener('resize', handleResize);
  
  // 延迟清理以确保所有操作完成
  setTimeout(() => {
    if (chartInstance) {
      try {
        // 先清除选项
        chartInstance.clear();
        // 然后销毁实例
        chartInstance.dispose();
      } catch (error) {
        console.warn('清理图表时出现警告:', error);
      } finally {
        chartInstance = null;
      }
    }
  }, 100);
});
</script>